﻿using Shop.Model.DB;
using Shop.Model.Goods;
using Shop.RemoteModel;
using Shop.RemoteModel.SpuGoods.Model;
using Shop.Repository.LinqHelper;
using WeDonekRpc.Client;
using WeDonekRpc.Helper;
using WeDonekRpc.Helper.IdGenerator;
using WeDonekRpc.Model;
using WeDonekRpc.SqlSugar;

namespace Shop.Repository.lmpl
{
    internal class GoodsRepository : ShopBaseRepository<DBGoods, long>, IGoodsRepository
    {
        public GoodsRepository (ISqlClientFactory factory) : base(factory)
        {
        }
        public Result[] Query<Result> (GoodsQuery query, IBasicPage paging, out int count) where Result : class
        {
            paging.InitOrderBy("Id", true);
            return base.Query<Result>(query.ToWhere(), paging, out count);
        }
        public long Add (GoodsSetArg arg)
        {
            DBGoods add = arg.ConvertMap<GoodsSetArg, DBGoods>();
            add.AddTime = DateTime.Now;
            add.Ver = 1;
            add.Id = IdentityHelper.CreateId();
            add.Status = GoodsStatus.起草;
            base.Insert(add);
            return add.Id;
        }
        public void Drop (long id)
        {
            if (!base.Update(a => a.IsDrop == true, a => a.Id == id))
            {
                throw new ErrorException("shop.goods.drop.fail");
            }
        }
        public void Public (long id, short len, decimal price)
        {
            if (!base.Update(a => new DBGoods
            {
                Status = GoodsStatus.发布中,
                PublicTime = DateTime.Now,
                SkuNum = len,
                Price = price
            }, a => a.Id == id))
            {
                throw new ErrorException("shop.goods.public.fail");
            }
        }
        public void Offshelf (long id)
        {
            if (!base.Update(a => new DBGoods
            {
                Status = GoodsStatus.下架,
                OffShelfTime = DateTime.Now
            }, a => a.Id == id))
            {
                throw new ErrorException("shop.goods.offshelf.fail");
            }
        }
        public Result[] GetTops<Result> ( TopGetArg arg ) where Result : class, new()
        {
            string orderBy = arg.SortName;
            if ( arg.IsDesc )
            {
                orderBy += " desc";
            }
            return base.GetTops<Result>(arg.ToWhere(), arg.Top, orderBy);
        }
        public void PublicComplete (long id)
        {
            if (!base.Update(a => new DBGoods
            {
                Status = GoodsStatus.已发布,
                Ver = Tools.GetRandom()
            }, a => a.Id == id))
            {
                throw new ErrorException("shop.goods.public.fail");
            }
        }
    }
}
